package com.RabbitMQ.topics.Customer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by thinkjoy on 2017/6/29.
 */
public class ReceiveLogsTopicTwo {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException,TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();
        //声明一个匹配模式的交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        String queuename=channel.queueDeclare().getQueue();
//        路由关键字,模糊匹配
        String[] roungtingKeys=new String[]{"*.*.rabbit", "lazy.#"};
//        绑定路由
        for (String rountkey:roungtingKeys){
            channel.queueBind(queuename,EXCHANGE_NAME,rountkey);
            System.out.println("ReceiveLogsTopicTwo exchange:" + EXCHANGE_NAME + ", queue:" + queuename + ", BindRoutingKey:" + rountkey);
        }
        System.out.println("ReceiveLogsTopicTwo Waiting for messages");
        Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message=new String(body,"UTF-8");
                System.out.println("ReceiveLogsTopicTwo Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queuename,true,consumer);
    }
}
